Kotlin is a new programming language created by JetBrains and targeting the JVM, Android and the browser. Kotlin is concise, safe, and fully interoperable with existing Java and JavaScript code. Kotlin helps avoid common errors such as NPEs and strives to make programming more pleasant. At the Google I/O conference, Google has announced official support for Kotlin as a language for developing Android applications, meaning that Kotlin development tools are now bundled with Android Studio. This cheat sheet will introduce you to the most important elements of the Kotlin syntax. To learn more, visit the Kotlin web site at kotlinlang.org.
Kotlin: What does it look like?
Source: kotlinlang.org
Basic Syntax
Hello World:
fun main(args: Array) {
println("Hello, World")
}
Declaring functions:
fun sum(a: Int, b: Int): Int {
return a + b
}
Functions with expression body:
fun sum(a: Int, b: Int) = a + b
Declaring variables:
v
al name = "Kotlin"
// can’t be changed
var age = 5
// can be changed
age++
Variables with nullable types:
var middleName: String? = null
// doesn’t compile
middleName.length
val length = middleName?.length ?: 0
// length or 0 if null
Control Structures
if statement (also replaces ternary operator):
fun max(a: Int, b: Int) = if (a > b) a else b
for loop:
for (element in list) {
println(element)
}
for loop with index:
for ((index, element) in elements.withIndex()) {
// String interpolation: $index, $element
println("Element at $index is $element")
}
when (replaces switch). when is an expression, like if
fun whenDemo(x: Number) = when(x) {
// Equality check
0 -> "Zero"
in 1..4 -> "Four or less"
// Range check
5, 6, 7 -> "Five to seven"
// Multiple values
is Byte -> "Byte"
// Type check
else -> "Some number"
}
when without expression:
fun whenDemo2(x: Number) = when {
x < 0 -> "Negative"
x == 0 -> "Zero"
else -> "Positive"
}
Classes
Primary constructor. val declares a read-only property, var –
a mutable one
class Person(val name: String, var age: Int)
// name is readonly, age is mutable
Inheritance:
open class Person(val name: String) {
open fun sayHello() = "Hello from $name"
}
class RussianPerson(name: String) : Person(name) {
override fun sayHello() = "Privet ot $name"
}
Properties with accessors:
class Person(val name: String, var age: Int) {
var birthYear: Int
get() = LocalDate.now().year - age
set(value) {
age = LocalDate.now().year - value
}
}
Autogenerated equals(), hashCode(), toString(), copy():
data class Person(val name: String, var age: Int)
val olderPerson = person.copy(age = person.age + 1)
Higher Order Functions
filter() and map():
val adultList = persons
.filter { it.age >= 18 }
.map { "${it.name} is ${it.age} years old" }
use() (replaces Java’s try with resources):
fun printLines(file: File) {
file.inputStream().bufferedReader().use { reader ->
for (line in reader.lineSequence()) {
println(line)
}
}
}
Adding Kotlin to Gradle
Regular project:
buildscript {
// …
ext.kotlin_version = ''
dependencies {
classpath "org.jetbrains.kotlin" +
"kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'kotlin'
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8"
}
Android project (buildscript block is same as above):
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7"
}
Kotlin and Twitter: How to work with streaming data